

import DateUtil from "../../engine/DateUtil";
import { Logger } from "../../engine/Logger";
import ViewBase from "../../engine/ViewBase";
import { HttpHelper } from "../../net/HttpHelper";
import { UserModel } from "../model/UserModel";
import { UIHelper } from "../util/UIHelper";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ViewGiveGemHistory extends ViewBase {


    private txtName: cc.Label;

    private userData: object
    private curPage: number = 1;
    private totalPage: number = 1
    private page_size: number = 4
    private dataList: Array<object> = []
    private totalNum: number = 0
    private defaultItemNode: cc.Node

    public onInitChild(userData: object) {
        this.userData = userData;
        this.curPage = 1
        this.defaultItemNode = this.findChild(this.node, "meberScrollView/view/content/defaultItemNode")
        this.txtName = this.getChild(this.node, "txtName", cc.Label)
        this.refresh()
        this.getInfo()
        let btnPre: cc.Node = this.findChild(this.node, "btnPre")
        UIHelper.onAddEvent(btnPre, () => {
            if (this.curPage > 1) {
                this.curPage--;
                this.getInfo()
            }
        })
        let btnNext: cc.Node = this.findChild(this.node, "btnNext")
        UIHelper.onAddEvent(btnNext, () => {
            if (this.curPage < this.totalPage) {
                this.curPage++
                this.getInfo()
            }
        })
    }

    private getInfo() {
        HttpHelper.get_give_history(UserModel.instance.userId, this.userData["userid"], this.page_size, this.curPage, (data, totalNum: number) => {
            Logger.log("getInfo=", data, totalNum)
            this.dataList = data
            this.totalNum = totalNum
            this.refresh()
        })
    }

    private refresh() {
        this.hideAllChildren(this.defaultItemNode.parent)
        this.totalPage = this.totalNum % this.page_size == 0 ? this.totalNum / this.page_size : Math.floor(this.totalNum / this.page_size) + 1;
        if (this.totalPage <= 0) {
            this.totalPage = 1;
        }
        this.txtName.string = "给" + this.userData["nick_name"] + "的赠送记录"
        let txtPage: cc.Label = this.getChild(this.node, "txtPage", cc.Label)
        txtPage.string = this.curPage + "/" + this.totalPage
        for (let i = 0; i < this.dataList.length; i++) {
            let itemNode: cc.Node = this.defaultItemNode.parent.children[i]
            if (!itemNode) {
                itemNode = cc.instantiate(this.defaultItemNode)
                itemNode.parent = this.defaultItemNode.parent;
            }
            itemNode.active = true
            let txtDesc: cc.Label = this.getChild(itemNode, "txtDesc", cc.Label)
            txtDesc.string = DateUtil.formatDateStr(new Date(this.dataList[i]["time"]).getTime()) + "赠送了" + this.dataList[i]["num"] + "钻石"
        }

    }

}
